package com.sl.au.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.service.EvaluateService;
import com.sl.au.repository.EvaluateRepository;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.Evaluate;
@Service("EvaluateService")
@Transactional
public class EvaluateServiceImpl extends BaseServiceImpl implements EvaluateService{

	@Autowired
	EvaluateRepository evaluateRepository;
	@Autowired

	@Override
	public EvaluateRepository getRepository()
	{
		return this.evaluateRepository;
	}
	
	@Override
	public List<Evaluate> getPage(int start, int length, String key, String orderName, Direction dir) {
		Page<Evaluate> pages = null;
		Pageable pageable = new PageRequest(start / length, length, dir, orderName);
		if(StringUtils.hasText(key)){
			pages=this.evaluateRepository.getByKey(key,pageable);
		}
		else{
			pages =this.evaluateRepository.findAll(pageable);
		}
		
		return pages.getContent();
	}
	
	@Override
	public int getCount(String key) {
		if (!StringUtils.hasText(key))
			return this.evaluateRepository.findAll().size();
		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE);
		return this.evaluateRepository.getByKey(key, pageable).getContent().size();
	}

	@Override
	public void updateEvaluate(String id, double value) {
		if(value > 0) {
			Evaluate evaluate = evaluateRepository.getInfoByBusinessseller(id); 
			double evaluateScale = evaluate.getEvaluateScale();
			evaluateScale = evaluateScale - value;
			evaluate.setEvaluateScale(evaluateScale);
			evaluateRepository.save(evaluate);
		}
	}

	@Override
	public List<Evaluate> getPage(int start, int length, String key, String role, String orderName, Direction dir) {
		Page<Evaluate> pages = null;
		Pageable pageable = new PageRequest(start / length, length, dir, orderName);
		if(StringUtils.hasText(key)){
			pages=this.evaluateRepository.getByKey(key, role, pageable);
		}
		else{
			pages =this.evaluateRepository.findAll(role, pageable);
		}
		
		return pages.getContent();
	}

	@Override
	public int getCount(String key, String role) {
		if (!StringUtils.hasText(key))
			return this.evaluateRepository.findCountAll(role);
		return this.evaluateRepository.getCountByKey(key, role);
	}
}
